'use client'

import { Avatar, Box } from '@mui/material'
import Divider from '@mui/material/Divider'
import List from '@mui/material/List'
import ListItem from '@mui/material/ListItem'
import ListItemButton from '@mui/material/ListItemButton'
import ListItemIcon from '@mui/material/ListItemIcon'
import ListItemText from '@mui/material/ListItemText'
import Typography from '@mui/material/Typography'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'

import { Logout } from '@/components/Logout'

import type { IUser } from '@/types/auth.types'

import { firstMenu } from '@/config/menu.config'

import { getUser } from '@/services/auth-storage.service'

export default function SidebarMenu({ open }: { open: boolean }) {
	const [user, setUser] = useState<IUser | null>(null)
	const { push } = useRouter()
	useEffect(() => setUser(getUser()), [])

	return (
		<>
			<List>
				{firstMenu.map((item, index) => (
					<ListItem
						key={index}
						disablePadding
						sx={{ display: 'block' }}
						onClick={() => push(item.url)}
					>
						<ListItemButton
							sx={{
								minHeight: 48,
								justifyContent: open ? 'initial' : 'center',
								px: 2.5
							}}
						>
							<ListItemIcon
								sx={{
									minWidth: 0,
									mr: open ? 3 : 'auto',
									justifyContent: 'center'
								}}
							>
								{item.icon}
							</ListItemIcon>
							<ListItemText
								primary={item.title}
								sx={{ opacity: open ? 1 : 0 }}
							/>
						</ListItemButton>
					</ListItem>
				))}
			</List>
			<Divider
				sx={{
					mb: 2
				}}
			/>
			<Box
				sx={{
					display: 'flex',
					justifyContent: open ? 'initial' : 'center',
					px: 2.5,
					alignItems: 'center'
				}}
			>
				<Avatar
					sx={{
						justifyContent: 'center',
						bgcolor: 'primary.main'
					}}
				>
					{user &&
						(user.first_name ? user.first_name.at(0) : user.username.at(0))}
				</Avatar>
				<Typography
					sx={{
						ml: 2,
						display: open ? 'block' : 'none'
					}}
				>
					{user && (user.first_name ? user.first_name : user.username)}
				</Typography>
				<Box
					sx={{
						ml: 2,
						display: open ? 'block' : 'none'
					}}
				>
					<Logout />
				</Box>
			</Box>
		</>
	)
}
